package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.OssTemplate;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    //按条件分页查询
    @GetMapping("dish/page")       //传入默认值
    public ResultInfo page(@RequestParam(value = "page", defaultValue = "0") Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                           String name) {

        Page<Dish> page = dishService.findByPage(pageNum, pageSize, name);

        return ResultInfo.success(page);
    }

    //回显菜品
    @GetMapping("category/list")
    public ResultInfo findBytype(Integer type) {

        List<Category> bytype = dishService.findBytype(type);
        return ResultInfo.success(bytype);
    }

    //新增菜品
    @PostMapping("/dish")
    public ResultInfo save(@RequestBody Dish dish) {


        dishService.save(dish);
        String dishKey="dish_"+dish.getCategoryId();
        redisTemplate.delete(dishKey);


        return ResultInfo.success("添加成功");
    }
        public void clean(String key){

            Set keys = redisTemplate.keys(key);

            redisTemplate.delete(keys);

        }
    //查询回显
    @GetMapping("/dish/{id}")
    public ResultInfo findById(@PathVariable long id) {

        Dish dish = dishService.findByid(id);

        return ResultInfo.success(dish);
    }

    //修改菜品
    @PutMapping("/dish")
    public ResultInfo update(@RequestBody Dish dish) {

        dishService.updateDish(dish);
           clean("dish_*");
        return ResultInfo.success();
    }

    //起售 停售
    @PostMapping("/dish/status/{status}")
    public ResultInfo update(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {

        ResultInfo statusDishResultInfo = dishService.statusDish(status, ids);
        clean("dish_*");
        return statusDishResultInfo;
    }

    //菜品删除
    @DeleteMapping("/dish")
    public ResultInfo deleDishByid(@RequestParam List<Long> ids) {

        ResultInfo dele = dishService.deleByid(ids);
        clean("dish_*");
        return dele;
    }

}
